package com.demo.interrupted;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Component(value = "WorkerRunnable")
public class WorkerRunnable implements Runnable {

    @Autowired
    @Qualifier("threadPool")
    ExecutorService executorService;
    @Override
    public void run() {
        while (Thread.currentThread().isInterrupted() == false){
            try {
                String m = TaskQueueHolder.get().take();
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("worker is busy!");
                        /*try {
                            Thread.currentThread().sleep(20*1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }*/
                        int fab = Fab.fab(78);
                        System.out.println(fab);
                        System.out.println("work is done!");
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
        Thread.currentThread().interrupted();
        executorService.shutdown();
        try {
            boolean shutdowned = executorService.awaitTermination(5, TimeUnit.SECONDS);
            if(!shutdowned){
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }
}
